<?php
/**
 * File Name: Setting.php
 *
 * Author: zl
 * Qq: 178417451
 * createTime 16/6/29 下午4:27
 */

namespace App\Models;

use DB;

class Setting extends BaseModel
{
    protected $table = "setting";
    protected $fillable = ['type', 'name', 'value'];
    public $timestamps = false;

    public function __construct()
    {
        parent::__construct();
    }

    public function getList($where, $fields = ['type', 'name', 'value'])
    {
        $res = $this;
        $res = $res->select($fields);
        $res = $res->where(function ($query) use ($where) {
            $field = array_keys($where)[0];
            foreach ($where[$field] as $v) {
                $query->orwhere($field, $v);
            }
        });
        $res = $res->multiOrder(['id' => 'desc']);
        $res = $res->get();

        //将数组处理为对应关系
        $data = [];
        foreach ($res as $ve) {
            $data[$ve['name']] = $ve['value'];
        }
        return $data;
    }

    public function getOne($where, $fields = '*')
    {
        return $this->_getOne($where, $fields);
    }


    public function addsetting($request)
    {
        foreach ($request as $sys => $values) {
            foreach ($values as $name => $value) {
                $where['type'] = $sys;
                $where['name'] = $name;
                $data = $where;
                $data['value'] = $value;
                $res = $this->upOrAdd($where, $data);
                if (!$res) {
                    return false;
                }
            }
        }
        return true;
    }


    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }

    /**
     * 添加或更新
     */
    public function upOrAdd($where, $data)
    {
        $res = $this->updateOrCreate($where, $data);
        return $res;
    }

    public function scopeWhereor($query, $where)
    {
        if (!is_array($where)) {
            return $query;
        }
        foreach ($where as $key => $value) {
            if (is_array($value)) {
                $query->orwhere($key, $value[0], $value[1]);
            } else {
                $query->orwhere($key, $value);
            }
        }
        return $query;
    }
}
